package com.localization;
import android.util.Log;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by Edward on 2017/1/7.
 */
public class SocketTcpClient implements SocketClientInterface {
    private Gateway gateway = null;
    private Selector selector = null;
    private SocketChannel tcpChannel = null;
    private ByteBuffer Read_byteBuffer = null;
    private ByteBuffer Send_byteBuffer = null;
    private InetSocketAddress address = null;
    private GatawayBuffer RxBuffer = new GatawayBuffer();

    public SocketTcpClient(Gateway gateway)
    {
        System.out.println("SocketTcpClient");
        this.gateway = gateway;
        this.selector = gateway.getSelector();
        Read_byteBuffer = ByteBuffer.allocate(2048);
        Send_byteBuffer = ByteBuffer.allocate(512);
    }

    @Override
    public void connect(String MAC,String url,int port)
    {
        System.out.println("connect");
        try {
            /*打开一个TCP */
            this.tcpChannel = SocketChannel.open();
            /*设置TCP noblocking*/
            this.tcpChannel.configureBlocking(false);
            /*设置tcp目标地址*/
            this.address = new InetSocketAddress(url,port);
            this.tcpChannel.connect(address);
            this.tcpChannel.register(this.selector,SelectionKey.OP_CONNECT|SelectionKey.OP_READ);
            this.gateway.register(MAC,this.tcpChannel,this);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public boolean isconnect()
    {
        return this.tcpChannel.isConnected();
    }

    @Override
    public void Process(SelectionKey key) {


        SocketChannel channel = (SocketChannel) key.channel();

        if(this.tcpChannel.equals(channel))
        {
            int bytesRead = 0;
            try{

                while((bytesRead = channel.read(Read_byteBuffer))>0) {
                    //InetSocketAddress address = (InetSocketAddress) channel.receive(Read_byteBuffer);
                    Log.d("Read From Gateway:",Utils.printHexString(Read_byteBuffer.array(),Read_byteBuffer.position())+"--"+Read_byteBuffer.position());
                    String Result= Utils.printHexString(Read_byteBuffer.array(),Read_byteBuffer.position());
                    int msize=0;
                    for(int i=0;;i++) {

                        int size = Integer.parseInt(Result.substring(4, 6), 16);
                        msize=msize+size;
                        if(msize==Read_byteBuffer.position()-(i+1)*4){
                            Log.d("一个包","一个包"+Result);
                            SocketCmdsDistribute.receive(Result);
                            break;
                        }else{
                            String Result1=Result.substring(0,2*(size+4));
                            Log.d("多个包","多个包"+Result1);
                            SocketCmdsDistribute.receive(Result1);
                            Result=Result.substring(2*(size+4));
                        }

                    }
                    Read_byteBuffer.clear();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void close() {
        try {
            tcpChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    @Override
    public int send(byte[] cmds) {
        int byteToSend = 0;
        //Utils.printHexString(cmds,cmds.length);
        Send_byteBuffer.clear();
        Send_byteBuffer.put(cmds);
        Send_byteBuffer.flip();
        //Utils.printHexString(Send_byteBuffer.array(),cmds.length);

        try {
           //if(this.tcpChannel.isConnected()) {
               System.out.println("isconnect");
               tcpChannel.write(Send_byteBuffer);
               //byteToSend = this.tcpChannel.write(Send_byteBuffer);
           //}
        }catch (Exception e) {
            e.printStackTrace();
        }
        return byteToSend;
    }

}
